package timing.ukulele.third.service.weixin;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.springframework.stereotype.Service;
import timing.ukulele.common.dictionary.YesOrNoEnum;
import timing.ukulele.data.third.data.weixin.WxMsgDTO;
import timing.ukulele.data.third.view.weixin.WxMsgVO;
import timing.ukulele.third.persistent.weixin.WxUser;
import timing.ukulele.third.config.mp.WxMpConfiguration;
import timing.ukulele.third.constant.WxConstant;
import timing.ukulele.third.convertor.weixin.WxMsgConverter;
import timing.ukulele.third.mapper.wexin.WxMsgMapper;
import timing.ukulele.third.persistent.weixin.WxApp;
import timing.ukulele.third.persistent.weixin.WxMsg;
import timing.ukulele.third.service.common.BaseOperatorService;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
public class WxMsgService extends BaseOperatorService<WxMsgMapper, WxMsg> {

    private final WxUserService wxUserService;
    private final WxAppService wxAppService;

    public IPage<WxMsgVO> getWxMsgPage(WxMsgDTO wxMsgDTO) {
        Page pageParm = new Page(wxMsgDTO.getCurrent(), wxMsgDTO.getPageSize());
        Page page = this.lambdaQuery()
                .eq(WxMsg::getAppId, wxMsgDTO.getAppId())
                .eq(WxMsg::getType, wxMsgDTO.getType())
                .page(pageParm);
        List<WxMsgVO> list = WxMsgConverter.INSTANCE.p2vList(page.getRecords());
        page.setRecords(list);
        return page;
    }

    /**
     * 清楚未读消息
     *
     * @param wxMsgDTO
     * @return
     */
    public Boolean clearNotRead(WxMsgDTO wxMsgDTO) {
        return this.lambdaUpdate()
                .eq(WxMsg::getAppId, wxMsgDTO.getAppId())
                .eq(WxMsg::getWxUserId, wxMsgDTO.getWxUserId())
                .eq(WxMsg::getReadFlag, YesOrNoEnum.NO.getValue())
                .set(WxMsg::getReadFlag, YesOrNoEnum.YES.getValue())
                .update();
    }

    public WxMsgVO getDetails(Long id) {
        WxMsg wxMsg = this.getById(id);
        return WxMsgConverter.INSTANCE.p2v(wxMsg);
    }

    public Boolean saveWxMsg(WxMsgDTO wxMsgDTO) throws WxErrorException {
        WxApp wxApp = wxAppService.getById(wxMsgDTO.getAppId());
        WxUser wxUser = wxUserService.getById(wxMsgDTO.getWxUserId());
        WxMsg wxMsg = WxMsgConverter.INSTANCE.d2p(wxMsgDTO);
        // 组装入库对象
        wxMsg.setAppName(wxApp.getName());
        wxMsg.setAppLogo(wxApp.getLogo());
        wxMsg.setNickName(wxUser.getNickName());
        wxMsg.setHeadImgUrl(wxUser.getHeadImgUrl());
        wxMsg.setCreateTime(LocalDateTime.now());
        wxMsg.setType(WxConstant.WX_MSG_TYPE_2);
        WxMpKefuMessage wxMpKefuMessage = null;
        if (WxConsts.KefuMsgType.TEXT.equals(wxMsg.getRepType())) {
            wxMsg.setRepContent(wxMsg.getRepContent());
            wxMpKefuMessage = WxMpKefuMessage.TEXT().build();
            wxMpKefuMessage.setContent(wxMsg.getRepContent());
        }
        if (WxConsts.KefuMsgType.IMAGE.equals(wxMsg.getRepType())) {
            wxMsg.setRepName(wxMsg.getRepName());
            wxMsg.setRepUrl(wxMsg.getRepUrl());
            wxMsg.setRepMediaId(wxMsg.getRepMediaId());
            wxMpKefuMessage = WxMpKefuMessage.IMAGE().build();
            wxMpKefuMessage.setMediaId(wxMsg.getRepMediaId());
        }
        if (WxConsts.KefuMsgType.VOICE.equals(wxMsg.getRepType())) {
            wxMsg.setRepName(wxMsg.getRepName());
            wxMsg.setRepUrl(wxMsg.getRepUrl());
            wxMsg.setRepMediaId(wxMsg.getRepMediaId());
            wxMpKefuMessage = WxMpKefuMessage.VOICE().build();
            wxMpKefuMessage.setMediaId(wxMsg.getRepMediaId());
        }
        if (WxConsts.KefuMsgType.VIDEO.equals(wxMsg.getRepType())) {
            wxMsg.setRepName(wxMsg.getRepName());
            wxMsg.setRepDesc(wxMsg.getRepDesc());
            wxMsg.setRepUrl(wxMsg.getRepUrl());
            wxMsg.setRepMediaId(wxMsg.getRepMediaId());
            wxMpKefuMessage = WxMpKefuMessage.VIDEO().build();
            wxMpKefuMessage.setMediaId(wxMsg.getRepMediaId());
            wxMpKefuMessage.setTitle(wxMsg.getRepName());
            wxMpKefuMessage.setDescription(wxMsg.getRepDesc());
        }
        if (WxConsts.KefuMsgType.MUSIC.equals(wxMsg.getRepType())) {
            wxMsg.setRepName(wxMsg.getRepName());
            wxMsg.setRepDesc(wxMsg.getRepDesc());
            wxMsg.setRepUrl(wxMsg.getRepUrl());
            wxMsg.setRepHqUrl(wxMsg.getRepHqUrl());
            wxMpKefuMessage = WxMpKefuMessage.MUSIC().build();
            wxMpKefuMessage.setTitle(wxMsg.getRepName());
            wxMpKefuMessage.setDescription(wxMsg.getRepDesc());
            wxMpKefuMessage.setMusicUrl(wxMsg.getRepUrl());
            wxMpKefuMessage.setHqMusicUrl(wxMsg.getRepHqUrl());
            wxMpKefuMessage.setThumbMediaId(wxMsg.getRepThumbMediaId());
        }
        if (WxConsts.KefuMsgType.NEWS.equals(wxMsg.getRepType())) {
            List<WxMpKefuMessage.WxArticle> list = new ArrayList<>();
            JSONObject content = JSON.to(JSONObject.class, wxMsg.getContent());// JSONUtil.parseObj(wxMsg.getContent());
            List<JSONObject> jSONArray = content.getJSONArray("articles").toList(JSONObject.class);
            WxMpKefuMessage.WxArticle t;
            for (Object object : jSONArray) {
                JSONObject jSONObject = JSON.parseObject(JSON.toJSONString(object));// JSONUtil.parseObj(JSONUtil.toJsonStr(object));
                t = new WxMpKefuMessage.WxArticle();
//                t.setTitle(jSONObject.getStr("title"));
//                t.setDescription(jSONObject.getStr("digest"));
//                t.setPicUrl(jSONObject.getStr("thumbUrl"));
//                t.setUrl(jSONObject.getStr("url"));

                t.setTitle(jSONObject.getString("title"));
                t.setDescription(jSONObject.getString("digest"));
                t.setPicUrl(jSONObject.getString("thumbUrl"));
                t.setUrl(jSONObject.getString("url"));
                list.add(t);
            }
            wxMsg.setRepName(wxMsg.getRepName());
            wxMsg.setRepDesc(wxMsg.getRepDesc());
            wxMsg.setRepUrl(wxMsg.getRepUrl());
            wxMsg.setRepMediaId(wxMsg.getRepMediaId());
            wxMsg.setContent(wxMsg.getContent());
            wxMpKefuMessage = WxMpKefuMessage.NEWS().build();
            wxMpKefuMessage.setArticles(list);
        }
        if (wxMpKefuMessage != null) {
            WxMpKefuService wxMpKefuService = WxMpConfiguration.getMpServiceByAppId(wxMsg.getAppId()).getKefuService();
            wxMpKefuMessage.setToUser(wxUser.getOpenId());
            wxMpKefuService.sendKefuMessage(wxMpKefuMessage);
            this.save(wxMsg);
        }
        return Boolean.TRUE;
    }

    public Boolean updateWxMsg(WxMsgDTO wxMsgDTO) {
        WxMsg wxMsg = WxMsgConverter.INSTANCE.d2p(wxMsgDTO);
        return this.updateById(wxMsg);
    }

    public Boolean deleteWxMsg(Long id) {
        return Boolean.TRUE;
    }

}
